// 日志工具类

interface LoggerOptions {
  debug?: boolean;
  role?: "HOST" | "CLIENT";
  prefix?: string;
}

const colors = {
  log: { background: "#e3f2fd", color: "#1976d2" }, // 浅蓝色
  error: { background: "#ffebee", color: "#d32f2f" }, // 浅红色
  warn: { background: "#fff8e1", color: "#f57c00" }, // 浅橙色
  info: { background: "#e0f2f1", color: "#00796b" }, // 浅青色
};

// HOST和CLIENT的颜色配置
const roleColors = {
  HOST: { background: "#000000", color: "#ffffff" }, // 黑色
  CLIENT: { background: "#28a745", color: "#ffffff" }, // 绿色
};

function getStyleConsole(type: keyof typeof colors, role?: string, prefix?: string): string[] {
  const { background, color } = colors[type];

  // 无胶囊
  if (!role && !prefix) {
    return [`%c`, `background: ${background}; color: ${color}; padding: 2px 4px; border-radius: 4px;`];
  }

  // 单色胶囊 - 只有role
  if (role && !prefix) {
    const roleColor = roleColors[role as keyof typeof roleColors];
    return [
      `%c${role}`,
      `background: ${roleColor.background}; color: ${roleColor.color}; padding: 2px 4px; border-radius: 4px;`,
    ];
  }

  // 单色胶囊 - 只有prefix
  if (!role && prefix) {
    return [`%c${prefix}`, `background: ${background}; color: ${color}; padding: 2px 4px; border-radius: 4px;`];
  }

  // 双色胶囊 - 有role和prefix
  if (role && prefix) {
    const roleColor = roleColors[role as keyof typeof roleColors];
    return [
      `%c${role}%c${prefix}`,
      `background: ${roleColor.background}; color: ${roleColor.color}; padding: 2px 4px; border-radius: 4px 0 0 4px;`,
      `background: ${background}; color: ${color}; padding: 2px 4px; border-radius: 0 4px 4px 0;`,
    ];
  }

  return [`%c`, ``];
}

export class Logger {
  private debugMode: boolean;
  private role?: string;
  private prefix?: string;

  constructor(options: LoggerOptions = {}) {
    this.debugMode = options.debug || false;
    this.role = options.role;
    this.prefix = options.prefix;
  }

  log(message: string, data?: any): void {
    if (this.debugMode) {
      console.log(...getStyleConsole("log", this.role, this.prefix), message, data || "");
    }
  }

  error(message: string, error?: any): void {
    console.error(...getStyleConsole("error", this.role, this.prefix), message, error || "");
  }

  warn(message: string, data?: any): void {
    console.warn(...getStyleConsole("warn", this.role, this.prefix), message, data || "");
  }

  info(message: string, data?: any): void {
    if (this.debugMode) {
      console.log(...getStyleConsole("info", this.role, this.prefix), message, data || "");
    }
  }
}
